package main

import (
	"bytes"
	"encoding/base64"
	"flag"
	"image/jpeg"
	"image/png"
	"io"
	"log"
	"os"
	"strconv"

	pb "git.oschina.net/sukibean/yolomonitor/protobuf"
	"golang.org/x/net/context"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
	"google.golang.org/grpc/grpclog"
)

var (
	tls                = flag.Bool("tls", false, "Connection uses TLS if true, else plain TCP")
	caFile             = flag.String("ca_file", "testdata/ca.pem", "The file containning the CA root cert file")
	serverAddr         = flag.String("server_addr", "127.0.0.1:50050", "The server address in the format of host:port")
	serverHostOverride = flag.String("server_host_override", "x.test.youtube.com", "The server name use to verify the hostname returned by TLS handshake")
)

func printDetectData(client pb.ImageDetectClient, req *pb.DetectRequest) {
	grpclog.Printf("Looking for DetectData within %v", req)
	stream, err := client.GetMultiObject(context.Background(), req)
	if err != nil {
		grpclog.Fatalf("%v.ListDetectData(_) = _, %v", client, err)
	}
	i := 0
	for {
		detect_obj, err := stream.Recv()
		if err == io.EOF {
			break
		}
		if err != nil {
			grpclog.Fatalf("%v.ListFeatures(_) = _, %v", client, err)
		}

		img_bytes, _ := base64.StdEncoding.DecodeString(detect_obj.GetType())
		mm, _ := jpeg.Decode(bytes.NewReader(img_bytes))
		// send_s3 := buf.Bytes()

		if err != nil {
			log.Fatal(err)
		}
		// bounds := m.Bounds()

		w, _ := os.Create("dddd" + strconv.Itoa(i) + ".png")
		defer w.Close()
		png.Encode(w, mm)

		i += 1
		// grpclog.Println(detect_obj)
	}
}

func main() {
	flag.Parse()
	var opts []grpc.DialOption
	if *tls {
		var sn string
		if *serverHostOverride != "" {
			sn = *serverHostOverride
		}
		var creds credentials.TransportCredentials
		if *caFile != "" {
			var err error
			creds, err = credentials.NewClientTLSFromFile(*caFile, sn)
			if err != nil {
				grpclog.Fatalf("Failed to create TLS credentials %v", err)
			}
		} else {
			creds = credentials.NewClientTLSFromCert(nil, sn)
		}
		opts = append(opts, grpc.WithTransportCredentials(creds))
	} else {
		opts = append(opts, grpc.WithInsecure())
	}
	conn, err := grpc.Dial(*serverAddr, opts...)
	if err != nil {
		grpclog.Fatalf("fail to dial: %v", err)
	}
	defer conn.Close()
	client := pb.NewImageDetectClient(conn)

	printDetectData(client, &pb.DetectRequest{
		"xx",
	})

}
